const ActivityModel = require("../model/activity");
const BaseController = require("./base/base");
const Result = require("../utils/result");
class ActivityController extends BaseController {
  constructor() {
    super();
    this.key = "xiaohuai";
  }
  // 获取活动列表
  findActivityList(req, res, next) {
    setTimeout(async () => {
      try {
        let { pagesize = 5, page = 1, activity_name = '', activity_state = 0, creator = '' } = req.query;
        pagesize *= 1
        page *= 1
        activity_state *= 1
        let _filter
        activity_state == 0 ? (_filter = { activity_name: { $regex: activity_name, $options: 'i' }, creator: { $regex: creator, $options: 'i' } }) : (_filter = { activity_name: { $regex: activity_name, $options: 'i' }, creator: { $regex: creator, $options: 'i' }, activity_state })
        let start = (page - 1) * pagesize;
        let list = await ActivityModel.find(_filter).limit(pagesize).skip(start)
        let total = await ActivityModel.countDocuments(_filter)
        res.json(Result.ok("success", { total, list }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 增加活动
  insert(req, res, next) {
    setTimeout(async () => {
      try {
        let { activity_name = '', activity_state = 1, creator = '', start_time } = req.body;
        activity_state *= 1
        if (!activity_name) return res.json(Result.fail("活动名不能为空"));
        const ret = await ActivityModel.create({ activity_name, activity_state, start_time, creator });
        res.json(!ret._id ? Result.fail("添加失败") : Result.ok("添加成功", ret))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 修改活动信息
  updateActivity(req, res, next) {
    setTimeout(async () => {
      try {
        const { id } = req.params;
        let ret = await ActivityModel.updateOne({ _id: id }, req.body);
        if (ret.matchedCount != 1) return res.json(Result.fail("修改失败", ret))
        res.json(Result.ok("修改成功", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 删除活动
  delById(req, res, next) {
    setTimeout(async () => {
      try {
        const { id } = req.params;
        let ret = await ActivityModel.deleteOne({ _id: id });
        res.json(!ret.deletedCount ? Result.fail("删除失败") : Result.ok("删除成功", ret))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
}
module.exports = new ActivityController().resolve();